<?php
class CodeManager extends CApplicationComponent {

	private $_numberFormatter;

	public static $classCodeMapping = array(
		'MaterialReceipt' => 'MRCP',
		'MaterialExpense' => 'MEXP',
		'AccountToken' => 'ACTN',
	);

	public static $redirectActionMapping = array(
		'MRCP' => 'materialReceipt/view',
		'MEXP' => 'materialReceipt/viewExpense',
		'ACTN' => 'accountToken/view',
	);

	protected function getNumberFormatter() {
		if ($this->_numberFormatter === null) {
			$this->_numberFormatter = Yii::app()->numberFormatter;
		}
		return $this->_numberFormatter;
	}

	public function getCode($model, $attribute = 'id', $numberPattern = '00000000') {
		if ($model === null || !is_object($model)) {
			return null;
		}
		$className = get_class($model);
		if (isset(self::$classCodeMapping[$className])) {
			$code = self::$classCodeMapping[$className];
			$id = $model->$attribute;
			return $code . $this->getNumberFormatter()->format($numberPattern, $id);
		} else {
			return null;
		}
	}

	public function redirect($code) {
		if (!preg_match_all('/^(\w{4})(\d{8})$/', $code, $matches)) {
			throw new CHttpException(400, '代码格式不正确');
		}
		$this->performRedirect($matches[1][0], intval($matches[2][0]));
	}

	public function findModel($code) {
		if (!preg_match_all('/^(\w{4})(\d{8})$/', $code, $matches)) {
			throw new CHttpException(400, '代码格式不正确');
		}
		$classes=array_keys(self::$classCodeMapping,$matches[1][0]);
		if(empty($classes)){
			throw new CHttpException(400, '代码格式不正确');
		}
		$className=$classes[0];
		$model=CActiveRecord::model($className)->findByPk($matches[2][0]);
		if($model===null){
			throw new CHttpException(404, '代码不存在');
		}
		return $model;
	}

	protected function performRedirect($code, $id) {
		if (isset(self::$redirectActionMapping[$code])) {
			Yii::app()->getController()
				->redirect(
					array(
						self::$redirectActionMapping[$code],
						'id' => $id
					));
		}

	}

	public function barCode($model, $attribute = 'id', $numberPattern = '00000000') {
		$code = $this->getCode($model);
		echo CHtml::image(
			Yii::app()->getController()
				->createUrl('dynamicImage/barcode', array(
					'text' => $code
				)), $code);
	}
}
